/**
 * 广告语管理
 */
define(['../../common/service'], function (http) {
    $.fn.select2.amd.require(['select2/selection/search'], function (Search) {
        var oldRemoveChoice = Search.prototype.searchRemoveChoice;
        Search.prototype.searchRemoveChoice = function () {
            oldRemoveChoice.apply(this, arguments);
            this.$search.val('');
        };

    });
    //业务处理
    var Adwords = function () {
    }
    Adwords.prototype = $.extend(Adwords.prototype, {
        init: function () {
            var _this = this;
            _this.$adwordsField = null;//创建广告语的field
            //列表管理
            //_this.listManager = new listManager();
            //_this.listManager.init();
            $('table[list-manager="listAdwordsByTags"]').listManager('init', {
                supportAjaxPage: true
                ,setTopVal:177//调整吸顶的高度,需要减去这个高度
                ,scrollDOM:$('.fmp-article')//监听滚动条
                ,isDevelopMode: false		//是否为开发模式，为true时将打印事件日志
                , basePath: ''			//当前基本路径[用于加载资源文件]
                , useDefaultStyle: false		//是否使用默认的table样式
                , animateTime: 300		//动画效果延时
                , minNum: 40					//宽度所允许的最小值
                , supportAdjust: true		//是否支持宽度调整
                , supportDrag: true 		//是否支持拖拽换位
                , supportConfig: true 		//是否支持配置列表功能[操作列是否可见]
                , supportSetTop: true		//是否支持表头置顶
                , autoLoadCss: false
                , pageCallback: function (query) {
                    $.extend(_this._query, query);
                    _this.getList();
                }
            }, function (query) {
                _this._query = {
                    pSize: query.pSize,
                    cPage: 1
                };
                _this._query.productId = '-1';
                _this._query.languageId = '-1';
                _this.getList();			//获取列表数据
                _this.bindCreateEvent();
                _this.bindDelEvent();			//绑定删除功能
                _this.bindSearchEvent();	//绑定搜索事件
            });

            _this.bindKeyUpEvent();
            _this.bindSubmitEvent();
            _this._initModalLanguageSelect(); 	//初始化弹出框的语言
            _this._initLanguageSelect(); 	//初始化语言
            _this.bindAppChangeEvent();     //绑定应用切换事件
            _this._initAppSelect();         //初始化应用数据
            _this._initAdWordsField();         //广告语标签
        },

        bindCreateEvent: function () {
            $("#btnCreate").unbind("click").click(function (e) {
                $("#modalCreate").modal("show");
            });
        }
        /*
         @绑定键盘收起事件【用于计算广告词字数、对阿拉伯语言进行特殊处理】
         */
        , bindKeyUpEvent: function () {
            var _area = $('textarea'),//字符串数字监控区:广告语和备注
                _len = '';
            _area.unbind("input");
            _area.bind("input", function () {
                var maxLength = $(this).attr('maxlength');
                var stringNumber = $(this).parent().find('.stringNumber');   //字符串数字显示区
                if (!stringNumber || stringNumber.length == 0) {
                    console.log('绑定键盘收起事件【用于计算广告词字数】时未捕获有效的DOM节点，已跳出');
                    return false;
                }
                _len = this.value.length;
                if (_len < 90) {
                    stringNumber.text(I18N.getText('createAdword', 'inputCharPre', (maxLength - _len)) + I18N.getText('createAdword', 'inputCharPost'));
                }
                else if (_len > 90 && _len < maxLength) {
                    stringNumber.text(I18N.getText('createAdword', 'showWordMsg'));
                }
                else if (_len >= maxLength) {
                    stringNumber.text(I18N.getText('createAdword', 'maxlength'));
                }
                if (_isAr(this.value)) {
                    $(this).attr('dir', 'rtl');
                } else {
                    $(this).removeAttr('dir', 'rtl');
                }
            });

            //验证是否为阿拉伯语言
            function _isAr(str) {
                //判断文字中是否含有阿拉伯语
                for (var i = 0; i < str.length; i++) {
                    var code = str.charCodeAt(i);
                    if (code > 0x600 && code < 0x6ff) {
                        return true;
                    }
                    if (code > 0xFE70 && code < 0xFEFF) {
                        return true;
                    }
                }
                return false;
            }
        }
        , bindSubmitEvent: function () {
            var that = this;
            var myForm = $('#myForm');
            var submitForm = $('.modal-footer .submitForm');
            var btnSubmitContinue = $('.modal-footer .submitAndContinue');

            var appArea = $('.app-area', myForm),
                languageArea = $('.language-area', myForm),
            //tags 	= myForm.find('input[name=tags]'),			//标签
                adWords = myForm.find('textarea[name=adWords]'),    //广告词
                remark = myForm.find('textarea[name=remark]');	    //备注

            //清除缓存
            //tags.select2('data',[]);
            adWords.val('');
            remark.val('');
            //绑定事件
            console.log(submitForm);
            submitForm.unbind("click").click(function () {
                submit(true)
            });
            btnSubmitContinue.unbind("click").click(function () {
                submit(false)
            });

            function submit(isClose) {
                //校验
                var _selectedApp = appArea.select2('data')[0];
                if (-1 == _selectedApp.id || '' == _selectedApp.id) {
                    Kit.alert2(I18N.getText('createAdword', 'selectApp'));
                    return false;
                }

                var _selectedLanguage = languageArea.select2('data')[0];
                if (-1 == _selectedLanguage.id || '' == _selectedLanguage.id) {
                    Kit.alert2(I18N.getText('createAdword', 'selectLanguage'));
                    return false;
                }
                // if ($.trim(adWords.val()) == '') {
                //     Kit.alert2(I18N.getText('createAdword', 'inputAdword'));
                //     adWords.focus();
                //     return false;
                // }
                var ctx = that.$adwordsField.getContent();
                if ($.trim(ctx) == '') {
                    Kit.alert2(I18N.getText('createAdword', 'inputAdword'));
                    return false;
                }

                var par = {
                    //tags					: tags.val()	|| '',
                    word: ctx || '',
                    productId:_selectedApp.id,
                    productId: _selectedApp.id,
                    fbConnectionObjectName: _selectedApp.text || '',
                    languageId: _selectedLanguage.id,                          //语言Id
                    language: _selectedLanguage.text || '',                 //语言
                    description: remark.val() || ''
                };
                http.do("/adwords/createAdword",
                    {param: JSON.stringify(par)}).then(function (res) {
                    if (res.flag == 'success') {
                        if(isClose){
                            Kit.alert_success(I18N.getText('createAdword', 'createSucceed'));
                        }else{
                            Kit.alert_success(I18N.getText('createAdword', 'createSucceedAndClose'));
                        }
                        //tags.select2('data',[]);
                        // adWords.val('');
                        // adWords.trigger("input");
                        $('#modalCreate .adwords-textarea').empty();
                        remark.val('');
                        remark.trigger("input");
                    } else {
                        Kit.alert2(res.msg || I18N.getText('createAdword', 'createFail'));
                    }
                });
                if (isClose) {
                    $("#modalCreate").modal('hide');
                    setTimeout(function() {
                        $('#searchAction').trigger('click');
                    },500);
                }
            }
        }
        /*
         @绑定搜索事件
         含搜索控件初始化
         */
        , bindSearchEvent: function () {
            var _this = this;
            //绑定搜索事件
            var searchAction = $('#searchAction');
            searchAction.unbind('click');
            searchAction.click(function () {
                _this._query.cPage = 1;
                _this._query.productId = $('select[name="app"]').select2("data")[0].id;
                _this._query.languageId = $('select[name="language"]').select2("data")[0].id;
                _this.getList();
            });

        }
        /*
         @获取列表数据
         */
        , getList: function () {
            var _this = this;
            var loadingArea = $('#grid').parents('div').eq(0);
            //common.Kit.loading.show(loadingArea);
            http.do('/adwords/getAdwordsList', {param: JSON.stringify(_this._query)}, 'GET').then(function (res) {
                var data = res.data;
                //操作DOM节点更换数据
                var _table = $('table[list-manager="listAdwordsByTags"]'),
                    _tbody = $('#grid', _table).empty(),
                    tmpHtml = '',
                    _list = data.adwords;
                if (data.paginator.length == 0) {
                    console.log('分页数据为空，已返回');
                    return false;
                }

                if (!_list || _list.length == 0) {
                    //if (data.paginator.cPage <= data.paginator.tPage) {
                    //	_table.listManager([{'resetTd': false, 'resetPageData': data.paginator}]);
                    //}
                    _table.listManager([{'resetTd': false, 'resetPageData': data.paginator}]);
                    console.log('列表为空，已返回');
                    return false;
                }

                for (var i = 0; i < _list.length; i++) {
                    var tmpWord = _list[i].word;
                    tmpWord = tmpWord.replaceAll("#b#n" ," ");
                    tmpWord = tmpWord.replace(/\{\{(.+?)\}\}/g,
                        function(t){
                            t=t.replace('{{','').replace('}}','');
                            var arr = t.split('|');
                            console.log(arr);
                            return '<span class="deco-tag">'+arr[1]+'</span>';
                        })
                    tmpHtml += '<tr>'
                        + '<td class="text-center">'
                        + ((data.paginator.cPage - 1) * data.paginator.pSize + i + 1)
                        + '</td>'
                        + '<td title="' + _list[i].word + '" class="text-left" style="font-size:15px">'
                        + tmpWord
                        + '</br><span style="color:rgb(134, 134, 134);font-size:12px;" title="' + (_list[i].description || '') + '">' + (_list[i].description || '') + '</span>'
                        + '</td>'
                        + '<td width="100" class="text-center">'
                        + '<a href="javascript:void(0);" class="delAction icon-btn" delId="' + _list[i].id + '"><i class="glyphicon glyphicon-trash"></i></a>'
                        + '</td>'
                        + '</tr>';
                }
                _tbody.html(tmpHtml);
                _table.listManager([{'resetTd': false, 'resetPageData': data.paginator}]);
            });
        }
        /*
         @绑定删除功能
         */
        , bindDelEvent: function () {
            var _this = this;
            var delConfirm = $('#delConfirm');
            if (!delConfirm || delConfirm.length == 0) {
                $('body').append('<div id="delConfirm" style="display:none;min-height:40px" title="' + I18N.getText('adwords', 'confirm') + '"><p>' + I18N.getText('adwords', 'delConfirm') + '</p></div>');
            }
            $('body').off('click', '.delAction');
            $('body').on('click', '.delAction', function () {
                var delAction = $(this);
                //$(this).attr("data-toggle","modal").attr("data-target","#delId");
                var par = {
                    id: delAction.attr('delId')
                }
                if (!par.id || $.trim(par.id) == '') {
                    console.log('获取userID失败，删除操作已停止');
                    return false;
                }
                $('#adwords-dialog').modal('show');
                $('#adwords-dialog').find('.deleteAdwordBtn').off('click');
                $('#adwords-dialog').find('.deleteAdwordBtn').on('click', delFn);

                function delFn() {
                    var loadingArea = $('#grid').parents('div').eq(0);
                    //common.Kit.loading.show(loadingArea);
                    http.do('/adwords/deleteAdword', {param: JSON.stringify(par)}, 'POST').then(function (res) {
                        if (res.flag == "fail") {
                            Kit.alert2(res.msg || I18N.getText('adwords', 'delFail'));
                        } else {
                            Kit.alert_success(I18N.getText('adwords', 'delSucceed'));
                            //计算删除之后的应当查询的页数
                            if (_this._query.cPage > 1) {
                                var _table = $('table[list-manager="listAdwordsByTags"]');
                                var _listManager = _table.data('listManager');
                                var _pageData = _listManager.pageData;
                                //cPage: 1, pSize: 20, tPage: 1, tSize: 2
                                _this._query.tSize = _pageData.tSize - 1;
                                _this._query.tPage = Math.ceil((_pageData.tSize - 1) / _pageData.pSize);
                                if (_this._query.cPage > _this._query.tPage) {
                                    _this._query.cPage -= 1;
                                }
                            }
                            _this.getList();
                        }
                    }, function (msg) {
                        Kit.alert2(msg || I18N.getText('adwords', 'delFail'));
                    });
                }
            });
        }
        /**
         * 绑定应用切换事件-应用与语言级联关系
         */
        , bindAppChangeEvent: function () {
            var self = this;
            var _app = $('select[name="app"]');
            _app.unbind("change");
            _app.on("change", function () {
                var param = {
                    productId: $(this).val(),
                    dicType :'adword'
                };
                var languageArea = $('.language-area'),
                    selectLanguage = $('.select-language');
                //common.Kit.loading.show(selectLanguage);
                http.do("/adwords/searchLanguage",
                    {param: JSON.stringify(param)}, 'GET').then(function (res) {
                    var data = res.data;
                    var tmpHtml = '<option value="-1">' + I18N.getText('adwords', 'selectLanguage') + '</option>';
                    $.each(data, function (index, dict) {
                        tmpHtml += '<option value="' + (dict.id || '') + '">'
                            + dict.name
                            + '</option>'
                    });
                    $('select[name="language"]').html(tmpHtml);
                    $('select[name="language"]').select2({
                        minimumResultsForSearch: Infinity
                    });
                });
            });
        }
        , _initAppSelect: function () {
            var appArea = $('.app-area');
            var par = {
                typeId: 2  //1、主页; 2、应用
            };
            http.do("/connectionobjects/searchAppsAndConfigurations",
                {param: JSON.stringify(par)}).then(function (res) {
                //data = _.sortBy(data,function (item) {return item.name.toLowerCase();});
                var tmpHtml = '<option value="-1">' + I18N.getText('adwords', 'selectApp') + '</option>';
                for (var i = 0; i < res.data.length; i++) {
                    tmpHtml += '<option value="' + (res.data[i].fbConnectionObjectId || '') + '">'
                        + res.data[i].name
                        + '</option>'
                }
                appArea.html(tmpHtml);
                appArea.select2();
                $('select[name="app"]').trigger("change");
            });
        }
        , _initLanguageSelect: function () {
            var languageArea = $('.language-area');
            languageArea.select2({
                minimumResultsForSearch: Infinity
            });


        }
        , _initModalLanguageSelect: function () {
            var languageArea = $('.language-area'),
                selectLanguage = $('.select-language');
            var par = {
                "type": "adword"
            };
            var loadingArea = languageArea.closest('div');
            Kit.loading.show(loadingArea);
            http.do("/search/getDictionary",
                {param: JSON.stringify(par)}).then(function (res) {
                var data = res.data;
                var tmpHtml = '<option value="-1">' + I18N.getText('createAdword', 'selectLanguage') + '</option>';
                $.each(data, function (index, dict) {
                    tmpHtml += '<option value="' + (dict.id || '') + '">'
                        + dict.name
                        + '</option>'
                });
                languageArea.html(tmpHtml);
                languageArea.select2({
                    minimumResultsForSearch: Infinity
                });
                Kit.loading.hide(loadingArea);
            }, function () {
                Kit.alert2(I18N.getText('createAdword', 'createFail'));
            });
        }

        , dispose: function () {
        }
        ,_initAdWordsField:function() {
            var _this = this;
            http.work('/ec/tags', 'POST').then(function (d) {
                if (d.flag == 'fail') {
                    Kit.alert2(d.errorMsg);
                    return;
                }
                _this.init_rich_tags(d.data,'dpaAdword');
            });


        }
        ,init_rich_tags:function(tags,name){
            var _this = this;
            var temp = [];
            $.each(tags,function(i,obj){
                 if(name == 'dpaAdword' && obj.supportDpaAdword == 1)
                    temp.push(obj);
            });
            var html = "";
            $.each(temp,function(i,o){
                html += '<button type="button" class="btn btn-default btn-xs set-field" data-val="'+ o.tag +'">'+ o.name +'</button>';
            });
            $('#modalCreate .set-fields').empty().append(html);
            _this.$adwordsField = $('#modalCreate .adwords-textarea').field();
            $('#modalCreate .set-fields button.set-field').off('click').on('click',function(e) {
                _this.$adwordsField.addTag({
                    val:$(this).data('val'),
                    text:$(this).text()
                });
            });
        }



    })

    return new Adwords();
});
